<template>
  <div :class="prefixCls">
    <Popover title="" trigger="click" :overlayClassName="`${prefixCls}__overlay`">
      <Badge :count="count" dot :numberStyle="numberStyle">
        <BellOutlined />
      </Badge>
      <template #content>
        <!--        <Tabs>-->
        <!--          <template v-for="item in listData" :key="item.key">-->
        <!--            <TabPane>-->
        <!--              <template #tab>-->
        <!--                {{ item.name }}-->
        <!--                <span v-if="item.list.length !== 0">({{ item.list.length }})</span>-->
        <!--              </template>-->
        <!--              &lt;!&ndash; 绑定title-click事件的通知列表中标题是“可点击”的&ndash;&gt;-->
        <!--              <NoticeList :list="item.list" v-if="item.key === '1'" @title-click="onNoticeClick" />-->
        <!--              <NoticeList :list="item.list" v-else />-->
        <!--            </TabPane>-->
        <!--          </template>-->
        <!--        </Tabs>-->

        <!--        <NoticeList :list="listData" />-->
      </template>
    </Popover>
    <audio ref="audio">
      <source src="../../../../../assets/audio/audio.mp3" type="audio/mpeg" />
      <!--      <source :src="audioPath1" type="audio/mpeg" />-->
    </audio>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, h, onMounted, ref } from 'vue'
  import { Popover, Tabs, Badge, notification, Button } from 'ant-design-vue'
  import { BellOutlined } from '@ant-design/icons-vue'
  import NoticeList from './NoticeList.vue'
  import { useDesign } from '/@/hooks/web/useDesign'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { listNotice } from '/@/api/notice'
  import { NoticeVO } from '/@/api/notice/model/noticeModel'
  import { useUserStore } from '/@/store/modules/user'
  // import { PropType } from 'vue/dist/vue'
  const userStore = useUserStore()
  const userInfo = userStore.getUserInfo
  export default defineComponent({
    components: { Popover, BellOutlined, Tabs, TabPane: Tabs.TabPane, Badge, NoticeList },
    // props: {
    //   listData1: {
    //     type: Array as PropType<NoticeVO[]>,
    //     default: () => [],
    //   },
    // },
    setup() {
      const { prefixCls } = useDesign('header-notify')
      const { createMessage } = useMessage()
      const listData = ref<NoticeVO[]>([])
      const audio = ref(null)
      const count = computed(() => {
        let count = 0
        // for (let i = 0; i < listData.value.length; i++) {
        //   // count += listData[i].list.length
        // }
        count = listData.value.length
        return count
      })

      function onNoticeClick(record: NoticeVO) {
        // createMessage.success('你点击了通知，ID=' + record.id)
        // // 可以直接将其标记为已读（为标题添加删除线）,此处演示的代码会切换删除线状态
        // record.titleDelete = !record.titleDelete
        console.log('点击了通知：', record)
      }

      onMounted(() => {
        list()
        init(userInfo.userId)
      })

      const path = 'ws://localhost:7412/websocket/'
      const init = (userId) => {
        const ws = new WebSocket(path + userId)
        //监听是否连接成功
        ws.onopen = () => {
          console.log('ws连接状态：', ws.readyState)
          //连接成功则发送一个数据
          ws.send('连接成功')
        }

        //接听服务器发回的信息并处理展示
        ws.onmessage = (data) => {
          console.log('接收到来自服务器的消息：')
          console.log(data)
          console.log(data.data)
          const notice = JSON.parse(data.data)
          const key = `open${Date.now()}`
          audio.value!.click()
          audio.value!.play()
          notification.open({
            message: notice['type'],
            description: notice['content'],
            btn: () =>
              h(
                Button,
                {
                  type: 'primary',
                  size: 'small',
                  onClick: () => notification.close(key),
                },
                { default: () => '去处理' },
              ),
            key,
          })
        }

        //监听连接关闭事件
        ws.onclose = () => {
          //监听整个过程中websocket的状态
          console.log('ws连接状态：' + ws.readyState)
        }

        //监听并处理error事件
        ws.onerror = function (error) {
          console.error('error', error)
        }
      }

      // const listData = ref<NoticeVO[]>([])

      const list = () => {
        listNotice().then((res) => {
          listData.value = res
        })
      }

      return {
        prefixCls,
        count,
        onNoticeClick,
        numberStyle: {},
        listData,
        audio,
      }
    },
  })
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-notify';

  .@{prefix-cls} {
    padding-top: 2px;

    &__overlay {
      max-width: 360px;
    }

    .ant-tabs-content {
      width: 300px;
    }

    .ant-badge {
      font-size: 18px;

      .ant-badge-multiple-words {
        padding: 0 4px;
      }

      svg {
        width: 0.9em;
      }
    }
  }
</style>
